package com.four.bmm.controller;

import com.four.bmm.entity.User;
import com.four.bmm.service.NewsService;
import com.four.bmm.service.UserService;
import com.four.bmm.util.DateUtil;
import com.four.bmm.util.NameUtil;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;
@WebServlet("/UploadHeaderServlet")
public class UploadHeaderServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SmartUpload su=new SmartUpload();
        javax.servlet.jsp.PageContext pageContext =javax.servlet.jsp.JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, true, 8192, true);
        su.initialize(pageContext);
        su.setCharset("UTF-8");
        JspFactory fac=JspFactory.getDefaultFactory(); // 在servlet中实例化
        su.initialize(fac.getPageContext(this,req,resp,null,false,JspWriter.DEFAULT_BUFFER,true));
        HttpSession session=req.getSession();
        User user=(User)session.getAttribute("loginuser");
        int userid=user.getUserid();
        String userid1=Integer.toString(userid);
        String changetime=NameUtil.getTime();
        String picname=changetime+userid1+".jpg";
        try {
            su.upload();
            /*su.save("F:\\BBS_Mybatis\\src\\main\\webapp\\images");*/
            com.jspsmart.upload.File file = su.getFiles().getFile(0);
            file.saveAs("src\\main\\webapp\\images\\"+picname);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        String userpic=su.getFiles().getFile(0).getFileName();

        System.out.println("===============picname=="+picname);
        UserService userService=new UserService();
        User user1=new User();
        user1.setUserid(userid);
        user1.setUserpic(picname);
        boolean b=userService.uploadHeader(user1);
        System.out.println(b);
        user.setUserpic(picname);
        session.setAttribute("loginuser",user);
        resp.sendRedirect("about.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
